package com.cosmosource.core.handler;

import com.cosmosource.core.common.Const;
import com.cosmosource.core.common.TenantConst;
import com.cosmosource.core.common.UserConst;
import com.cosmosource.core.utils.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * cosmo
 */
@Component
@Slf4j
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

    // 获取配置文件中的配置子平台地址
    private final String subPlatformUrl;

    public LoginHandlerInterceptor(@Value("${cosmo.platform.url.sub}") String subPlatformUrl) {
        this.subPlatformUrl = subPlatformUrl;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从获取的token中解析信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof Map)) {
            log.info("无法获取到token信息");
            return false;
        }
        Map userInfoMap = (Map) principal;

        // 让异步线程能获取到request数据
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(attributes, true);

        Object userIdObj = userInfoMap.get("userId");
        Object clientId = userInfoMap.get(Const.CLIENT_ID);
        if (userIdObj == null && clientId != null) {
            // 将客户端ID保存到request作用域
            request.setAttribute(Const.CLIENT_ID, clientId);
            return true;
        }

        String userId = String.valueOf(userIdObj);
        // 将userId和锁对象保存到request作用域
        request.setAttribute(UserConst.USER_ID, userId);
        request.setAttribute(Const.LOCK, new byte[]{});
        request.setAttribute(TenantConst.TENANT_ID, userInfoMap.get("tenantId"));

        // 将用户名和显示名加入到日志打印属性中
        String username = String.valueOf(userInfoMap.get("username"));
        String displayName = String.valueOf(userInfoMap.get("displayName"));
        String tenantId = String.valueOf(userInfoMap.get("tenantId"));
        MDC.put("displayName", username);
        MDC.put("username", displayName);
        MDC.put("tenantId", tenantId);

        try {
            RestTemplateUtil restTemplateUtil = new RestTemplateUtil();
            String token = request.getHeader("Authorization");
            token = token.replace("bearer ", "").trim();
            if (token != null && !token.isEmpty()) {
                String url = subPlatformUrl + "/cac/v1/sync/token?" + "token=" + token;
                restTemplateUtil.get(url, String.class, new HashMap<>());
            }
        } catch (Exception e) {

        }
        return true;
    }

}
